package com.example.api.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.io.Serializable;

/**
 * Feign调用添加token
 * */
@Configuration
@Slf4j
public class FeignRequestConfig implements WebFilter, RequestInterceptor {

    @Resource
    private TokenBean tokenBean;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String token = serverHttpRequest.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        tokenBean.setToken(token);
        return chain.filter(exchange);
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("token is {}", tokenBean.getToken());
        requestTemplate.header(HttpHeaders.AUTHORIZATION, tokenBean.getToken());
    }
}

@Component
@Data
class TokenBean implements Serializable{
    private String token;
}